import { defineStore } from "pinia";
import { LoginAPI, UserInfoAPI, LogoutAPI } from "@/network/user";
import { loginFormData, loginResponseData, userInfoResponseData } from "@/network/user/type";
import { UserState } from "./types/type";
import {SET_TOKEN, GET_TOKEN, REMOVE_TOKEN} from '@/utils/token'
// 引入导出的路由
import {constRoute, asyncRoute, anyRoute} from '@/router/routes'
import router from "../../router";
// 引入深拷贝方法
import cloneDeep from 'lodash/cloneDeep'

// 用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
   return asyncRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
               item.children = filterAsyncRoute(item.children, routes)
            }
            return true
        }
    })
}
export const useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            token: GET_TOKEN(),
            menuRoutes: constRoute, // 根据路由生成菜单的数组
            username: '',
            avatar: '',
            buttons: [] // 存储当前用户是否包含某一个按钮
        }
    },
    actions: {
        async userLogin(data: loginFormData) {
            const res: loginResponseData = await LoginAPI(data)
            // console.log(res);
            if (res.code === 200) {
                this.token = (res.data as string) // 断言
                // 本地存一份
                // 封装本地存储方法
                // localStorage.setItem('TOKEN', (res.data as string))
                SET_TOKEN(res.data as string)
                // 当前async函数返回一个成功的promise
                return 'ok';
            } else {
                return Promise.reject(new Error(res.data))
            }

        },
       async userInfo() {
           const res: userInfoResponseData = await UserInfoAPI()
           console.log(res);
           if (res.code === 200) {
            this.username = res.data.name
            this.avatar = res.data.avatar
            this.buttons = res.data.buttons
            // 计算当前用户需要展示的异步路由
            // 深拷贝
            const userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute), res.data.routes)
            // 展示菜单的数据
            this.menuRoutes = [ ...anyRoute, ...constRoute, ...userAsyncRoute,];
            // 获取所有注册的路由对象
            // console.log(router.getRoutes());
            //  目前路由器管理的只有常量路由，用户计算完毕异步路由，需要注册
            [...userAsyncRoute, ...anyRoute].forEach(route => {
                router.addRoute(route)
            })
            
            return 'ok'
           } else {
            return Promise.reject(new Error(res.message))
           }
        },
       async userLogout() {
            // 退出登录请求
            const res: any = await LogoutAPI()
            // console.log(res);
            if (res.code === 200) {
                this.token = ''
                this.username = ''
                this.avatar = ''
                REMOVE_TOKEN()
                return 'ok'
            } else {
                return Promise.reject(new Error(res.message))
            }
            
        }
    },
    getters: {

    }
})